<script setup lang="js">
import {ref, onMounted} from 'vue'
import {CopyOutlined} from '@ant-design/icons-vue';
import {message} from 'ant-design-vue';

const iframeRef = ref(null);
const apiBase = ref("http://127.0.0.1:8888")
const chatId = ref('')
const body = ref('')
const htmlBody = ref('')
const title = ref('')
const chatType = ref(0)
const loadMsg = ref('')
const open = ref(false);
const showChat = ref(false);
const copyId = ref("")

const sendMsg = () => {
  const iframe = iframeRef.value;
  if (iframe) {
    console.log("发送消息：")
    setTimeout(function () {
      // 发送消息到 iframe
      iframe.contentWindow.postMessage({
        chatId: chatId.value,
        title: title.value,
        chatType: chatType.value
      }, '*'); // 确保目标源与 iframe 的源匹配
    }, 1000)
  }
}


onMounted(() => {
  chrome.runtime.onMessage.addListener((request) => {
    if (request.type === 'bodyData') {
      body.value = request?.body
      htmlBody.value = encodeURIComponent(encodeURIComponent(request?.htmlBody));
      title.value = request?.title
      showChat.value = false
      chatId.value = ''
      loadMsg.value = ''
      message.info('页面切换:' + title.value);
    }
  })
})


const genHtmlData = () => {

  message.info('链接生成中');
  copyId.value = ''

  fetch(apiBase.value + '/api/addConfData', {
    method: 'POST',  // 请求方法为 POST
    headers: {
      'Content-Type': 'application/json'  // 设置请求头，告诉服务器传送的是 JSON 数据
    },
    body: JSON.stringify({  // 请求体：将 JavaScript 对象转化为 JSON 字符串
      html: htmlBody.value,
      text: body.value,
      title: title.value
    })
  })
      .then(response => response.json())  // 解析响应为 JSON
      .then(data => {
        if (data.data) {
          open.value = true
          copyId.value = data.data;
        }
        message.info('链接生成完成');
        console.log('Success:', data);  // 处理响应数据
      })
      .catch(error => {
        message.info('链接生成失败');
        console.error('Error:', error);  // 错误处理
      });
}


const newChat = (api) => {

  loadMsg.value = "加载中..."

  switch (api) {
    case "getChat":
      chatType.value = 1
      break;
    case "getKimiChat":
      chatType.value = 2
      break;
    case "getQwChat":
      chatType.value = 3
      break;
  }

  fetch(apiBase.value + '/api/' + api, {
    method: 'POST',  // 请求方法为 POST
    headers: {
      'Content-Type': 'application/json'  // 设置请求头，告诉服务器传送的是 JSON 数据
    },
    body: JSON.stringify({  // 请求体：将 JavaScript 对象转化为 JSON 字符串
      data: body.value,
    })
  })
      .then(response => response.json())  // 解析响应为 JSON
      .then(data => {
        if (data.data) {
          chatId.value = data.data;
          showChat.value = true
          sendMsg()
        }
        console.log('Success:', data);  // 处理响应数据
      })
      .catch(error => {
        console.error('Error:', error);  // 错误处理
      });


}

</script>

<template>
  <main>
    <div style="padding: 10px;font-size: 20px;" v-if="!chatId">{{ title }}</div>
<!--    <div class="btn" v-if="!chatId&&!loadMsg" style="cursor: pointer" @click="newChat('getChat')">常规对话</div>-->
<!--    <div class="btn" v-if="!chatId&&!loadMsg" style="cursor: pointer" @click="newChat('getKimiChat')">Kimi对话</div>-->
    <div class="btn" v-if="!chatId&&!loadMsg" style="cursor: pointer" @click="newChat('getQwChat')">千问对话</div>
    <div class="btn" v-if="!chatId&&!loadMsg" style="cursor: pointer" @click="newChat('getDsChat')">DeepSeek对话</div>
    <div class="btn" v-if="!chatId&&!loadMsg" style="cursor: pointer" @click="genHtmlData">复制当前内容</div>

    <div class="btn" v-if="!chatId&&loadMsg" @click="newChat('getDsChat')">{{ loadMsg }}</div>

    <iframe ref="iframeRef" @load="sendMsg" v-if="chatId&&showChat" id="chat-iframe" :src="apiBase"
            style="width: 100%;height: 92vh;border: none"></iframe>


    <a-modal v-model:open="open" title="内容页面" @ok="handleOk">

      <div>
        <a-form-item label="文本内容">
          <a-input-group compact>
            <a-input :value="apiBase+'/api/getConfDataText?id='+copyId" />
          </a-input-group>
        </a-form-item>
        <a-form-item label="网页内容">
          <a-input-group compact>
            <a-input :value="apiBase+'/api/getConfDataHtml?id='+copyId"/>
          </a-input-group>
        </a-form-item>
        <a-form-item label="JSON内容">
          <a-input-group compact>
            <a-input :value="apiBase+'/api/getConfDataJson?id='+copyId"/>
          </a-input-group>
        </a-form-item>
      </div>
    </a-modal>

  </main>
</template>

<style>
:root {
  font-family: system-ui,
  -apple-system,
  BlinkMacSystemFont,
  'Segoe UI',
  Roboto,
  Oxygen,
  Ubuntu,
  Cantarell,
  'Open Sans',
  'Helvetica Neue',
  sans-serif;

  color-scheme: light dark;
  background-color: #242424;
}

@media (prefers-color-scheme: light) {
  :root {
    background-color: #fafafa;
  }

  a:hover {
    color: #337cff;
  }
}

body {
  min-width: 20rem;
}

main {
  text-align: center;
  padding: 1em;
  margin: 0 auto;
}

h3 {
  color: #337cff;
  text-transform: uppercase;
  font-size: 1.5rem;
  font-weight: 200;
  line-height: 1.2rem;
  margin: 2rem auto;
}

a {
  font-size: 0.5rem;
  margin: 0.5rem;
  color: #cccccc;
  text-decoration: none;
}

.btn {
  width: 50vw;
  margin: 10px auto;
  padding: 15px 30px;
  font-size: 16px;
  font-weight: bold;
  text-transform: uppercase;
  border: none;
  border-radius: 50px;
  background-color: #337cff;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.3s;
}

.btn:hover {
  background-color: #337cff;
  transform: scale(1.1);
}

.btn:active {
  background-color: #337cff;
  transform: scale(1);
}

.btn:focus {
  outline: none;
}
</style>
